﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;

namespace Universe.CrossIO
{
    public class Writer
    {
        public static void JWrite(BinaryWriter writer, bool value)
        {
            writer.Write((byte)(value ? 1 : 0));
        }

        public static void JWrite7Bit(BinaryWriter writer, long value)
        {
            while (value >= 0x80)
            {
                writer.Write((byte) (0x80 | (value & 0x7F)));
                value = value >> 7;
            }
            writer.Write((byte) (value & 0x7F));
        }

        public static void JWrite(BinaryWriter writer, long value)
        {
            Byte[] bytes = BitConverter.GetBytes(value);
            Array.Reverse(bytes);
            writer.Write(bytes);
        }

        public static void JWrite(BinaryWriter writer, int value)
        {
            Byte[] bytes = BitConverter.GetBytes(value);
            Array.Reverse(bytes);
            writer.Write(bytes);
        }

        public static void JWrite(BinaryWriter writer, short value)
        {
            Byte[] bytes = BitConverter.GetBytes(value);
            Array.Reverse(bytes);
            writer.Write(bytes);
        }

        public static void JWrite(BinaryWriter writer, Color color)
        {
            JWrite(writer, color == Color.Empty ? -1 : color.ToArgb());
        }

        public static void JWrite(BinaryWriter writer, string s)
        {
            if (s == null)
                writer.Write((byte) 0);

            else
            {
                long len = s.Length;
                JWrite7Bit(writer, (long) (1 | (len << 1)));

                foreach (char c in s)
                {
                    JWrite7Bit(writer, (long)(int)c);
                }
                
            }
        }

        public static void JWrite(BinaryWriter writer, Guid g)
        {
            writer.Write((byte)(g == Guid.Empty ? 1 : 0));
            byte[] bytes = g.ToByteArray();
            writer.Write(bytes);
        }

        public static void JWrite(BinaryWriter writer, decimal value)
        {
            JWrite(writer, (long) (value*10000));
        }

        public static void JWrite(BinaryWriter writer, DateTime date)
        {
            JWrite(writer, (long) (date - Constants.JZeroDate).TotalMilliseconds);
        }

        public static void JWriteDay(BinaryWriter writer, DateTime day)
        {
            int dayKey = day.Year*366 + day.DayOfYear - 1;
            byte int8 = (byte) (dayKey & 0xFF);
            short int16 = (short) (dayKey >> 8);
            byte[] bytesInt16 = BitConverter.GetBytes(int16);
            Array.Reverse(bytesInt16);
            writer.Write(int8);
            writer.Write(bytesInt16);
        }
    }
}
